# SSH 免密登录配置脚本
# 使用方法: .\setup-ssh-key.ps1

$SERVER_IP = "154.219.117.72"
$SERVER_USER = "root"

Write-Host "设置 SSH 免密登录..." -ForegroundColor Cyan
Write-Host ""

# 检查是否已有 SSH 密钥
$sshKeyPath = "$env:USERPROFILE\.ssh\id_rsa.pub"

if (-not (Test-Path $sshKeyPath)) {
    Write-Host "未找到 SSH 密钥,正在生成..." -ForegroundColor Yellow
    ssh-keygen -t rsa -b 4096 -f "$env:USERPROFILE\.ssh\id_rsa" -N '""'
    Write-Host "SSH 密钥生成成功!" -ForegroundColor Green
}

# 复制公钥到服务器
Write-Host "`n正在复制公钥到服务器..." -ForegroundColor Yellow
Write-Host "请输入服务器密码:" -ForegroundColor Cyan

type $sshKeyPath | ssh ${SERVER_USER}@${SERVER_IP} "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"

if ($LASTEXITCODE -eq 0) {
    Write-Host "`n配置成功!" -ForegroundColor Green
    Write-Host "现在可以免密登录: ssh ${SERVER_USER}@${SERVER_IP}" -ForegroundColor Cyan
} else {
    Write-Host "`n配置失败,请检查网络和服务器设置" -ForegroundColor Red
}
